package com.hjy.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/*
* HTTP协议
HTTP协议在请求行请求头中都有很多的内容，自己实现较为困难，可以使用HttpServerCodec作为服务器端的解码器与编码器，来处理HTTP请求

// HttpServerCodec 中既有请求的解码器 HttpRequestDecoder 又有响应的编码器 HttpResponseEncoder
// Codec(CodeCombine) 一般代表该类既作为 编码器 又作为 解码器
public final class HttpServerCodec extends CombinedChannelDuplexHandler<HttpRequestDecoder, HttpResponseEncoder>
        implements HttpServerUpgradeHandler.SourceCodec
* */
public class HttpServer {

    static final Logger log = LoggerFactory.getLogger(HttpServer.class);

    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        //作为服务器 使用HttpServerCodec 作为编码和解码器
                        channel.pipeline().addLast(new HttpServerCodec());
                        //服务器只处理HttpRequest
                        channel.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpRequest request) throws Exception {
                                //获取请求的 uri
                                log.debug(request.uri());

                                //设置完整响应，设置版本号和状态码
                                DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
                                //设置响应内容 中文字符显示乱码
                                byte[] bytes = "<H1>Hi 金玉</H1>".getBytes(StandardCharsets.UTF_8);
                                //设置响应体长度，避免浏览器一直接受响应内容
                                response.headers().setInt("content-length", bytes.length)
                                        //中文栾曼需要设置字符集
                                        .set("Content-Type", "text/html;charset=UTF-8");
                                //设置响应体
                                response.content().writeBytes(bytes);

                                //写回响应
                                channelHandlerContext.writeAndFlush(response);
                            }
                        });
                    }
                })
                .bind(8080);

    }

}
